package com.jx.lcs.util.export;

import java.util.Iterator;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * 导出 excel
 * <p>
 * 使用 Map<String, Object> 渲染数据
 * 
 * 示例_1，输出一个 sheet: <br/>
 * List<Map<String, Object>> dataSet = new ArrayList<>(); <br/>
 * ...装配数据 <br/>
 * 
 * SheetDefination<Map<String, Object>> defination = new SheetDefination<>(); <br/>
 * defination.setSheetTitle("sheet标题"); <br/>
 * defination.setHeaders(new String[] {"header_1", "header_2", "header_3"}); br/>
 * defination.setDataKeys(new String[] {"key_1", "key_2", "key_3"}); <br/>
 * defination.setDataset(dataSet); <br/>
 * 
 * ExportExcel<Map<String, Object>> exportExcel = new ExportExcel4Map(); <br/>
 * OutputStream out = new FileOutputStream("E://a.xls"); <br/>
 * exportExcel.export(defination, out); <br/>
 * out.close();
 * 
 * 示例_2，输出 多个 sheet: <br>
 * List<Map<String, Object>> dataSet_1 = new ArrayList<>(); <br/>
 * ...装配数据 <br/>
 * List<Map<String, Object>> dataSet_n = new ArrayList<>(); <br/>
 * ...
 * 
 * SheetDefination<Map<String, Object>> defination_1 = new SheetDefination<>(); <br/>
 * ... <br/>
 * SheetDefination<Map<String, Object>> defination_n = new SheetDefination<>(); <br/>
 * ...
 * 
 * List<SheetDefination<Map<String, Object>>> definationList = new ArrayList<>(); <br/>
 * definationList.add(defination_1); <br/>
 * ... <br/>
 * definationList.add(defination_n);
 * 
 * ExportExcel<Map<String, Object>> exportExcel = new ExportExcel4Map(); <br/>
 * OutputStream out = new FileOutputStream("E://b.xls"); <br/>
 * exportExcel.export(definationList, out); <br/>
 * out.close();
 * 
 * @author sunlt
 * @date 2015.07.15
 */
public class Excel4MapExporter extends ExcelExporter<Map<String, Object>> {

  /**
   * 渲染Map数据
   * 
   * @param workbook 工作簿
   * @param sheet 单
   * @param defination sheet定义
   */
  @Override
  protected void renderData(HSSFWorkbook workbook, HSSFSheet sheet,
      SheetDefination<Map<String, Object>> defination) {

    Iterator<Map<String, Object>> dataIterator = defination.getDataset().iterator();
    HSSFRow row;
    int index = 0;
    while (dataIterator.hasNext()) {
      index++;
      row = sheet.createRow(index);

      Map<String, Object> element = dataIterator.next();
      String[] dataKeys = defination.getDataKeys();
      for (int i = 0; i < dataKeys.length; i++) {
        HSSFCell cell = row.createCell(i);
        cell.setCellStyle(createDataStyle(workbook));
        HSSFRichTextString text = new HSSFRichTextString(element.get(dataKeys[i]).toString());
        cell.setCellValue(text);
      }
    }
  }

}
